package design_pattern.proxy_pattern.dynamic_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Cheng Jun
 * Description: jdk动态代理
 * InvocationHandler 调用处理器
 * @version 1.0
 * @date 2022/7/20 20:48
 */
public class JDK_DProxy implements InvocationHandler {
    // 目标对象（被代理的对象）
    private Object target;
    // 代理对象 proxyInstance 代理 target
    private Object proxyInstance;

    // 为什么要传 Object proxy? 在方法里面也不用proxy调用方法，因为会造成死循环
    // proxy – the proxy instance that the method was invoked on 代理对象
    // proxy == proxyInstance
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("调用方法前 " + method.getName());
        System.out.println(proxy.getClass());
        // 因为 hashCode() 也被代理了，所以这样写，会造成死循环
        // System.out.println(proxy.hashCode());
        System.out.println("proxyInstance == proxy " + (proxyInstance == proxy));
        Object invokeRes = method.invoke(target, args);
        System.out.println("调用方法后 " + method.getName());
        return invokeRes;
    }

    public Object getProxy(Object target) {
        this.target = target;
        Object proxyInstance = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
        this.proxyInstance = proxyInstance;
        return proxyInstance;
    }
}
